var categoryDAL = require('../DAL/categoryDAL');
var productDAL = require('../DAL/productDAL');
var cartDAL = require('../DAL/cartDAL');
var collectDAL = require('../DAL/collectDAL');
var CartInfo = require('../Model/CartInfo');
var async = require('async');

function productController(app) {
	// body...
	/* GET home page. */
	//app.get方法第一个参数是我们添加网站可以请求的地址
	//商品展示页面
	app.get('/product/:id', function(req, res) {
		var product_id = parseInt(req.params.id);

		//res.render方法的第一个参数是我们请求地址对应的网页文件名
		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});

			}, //控制流程2:根据产品ID获取产品所有信息
			product: function(done) {
				productDAL.getGoodsById(product_id, function(product) {
					done(null, product);
				});
			},
			userInfo: function(done) {
				var userInfo = req.session.customer;
				done(null, userInfo);
			}
		}, function(err, results) {

			//console.log(results.product);
			//res.setHeader(200, {"Content-Type": "text/html"});
			res.render('Product/product', {
				categorylist: results.categorylist,
				product: results.product[0],
				userInfo: results.userInfo
			});

		});

	});

	app.get('/search', function(req, res) {

		var q = req.query.q;
		var currentpage = req.query.js;

		if(q == null || currentpage == null) {
			res.redirect('/search?q=&js=1');
		}

		console.log('key:' + q);
		console.log('pager:' + currentpage);

		//分页方法
		//定义分页参数
		//var currentpage = 1; //当前页
		var pagercounts = 1; //页面总数
		var previouspage = 1; //上一页
		var nextpage = 1;
		//设置分页 每页显示数据条数
		var pageSize = 20;
		var userInfo = req.session.customer;

		//如果搜索结果为空则返回空数据集
		if(q == null || q == '') {
			q = '';
			res.render('search', {
				productlist: '',
				currentpage: currentpage,
				previouspage: previouspage,
				nextpage: nextpage,
				pageSum: pagercounts,
				q: q,
				userInfo: userInfo
			});
		} else {
			//应用async模块的api:parallel处理并行无关联操作
			async.parallel({ //控制流程1:搜索
				productlistPager: function(done) {

					productDAL.searchGoodsByKey(q, currentpage, pageSize, function(productlist) {						
						done(null, productlist);
					});
				}, //控制流程2:用户信息
				userInfo: function(done) {					
					var userInfo = req.session.customer;
					done(null, userInfo);
				}, //控制流程3 当前分类商品总数
				goodsCounts: function(done) {
					productDAL.getGoodsCountsByKey(q, function(count) {						
						done(null, count);
					});
				}
			}, function(err, results) {

				//将上面几个步骤数据操作并行处理，然后在这里一起操作，提供运行效率
				var counts = parseInt(results.goodsCounts);

				//分页信息处理
				//计算总页数
				if((counts % pageSize) > 0) {
					//有余数，数据不足一整页
					pagercounts = parseInt(counts / pageSize) + 1;
				} else {
					//数据正好填满整页
					pagercounts = parseInt(counts / pageSize);
				}
				//设置上一页
				if(currentpage <= 1) {
					previouspage = 1;
				} else {
					previouspage = currentpage - 1;
				}
				//设置下一页
				if(currentpage >= pagercounts) {
					nextpage = pagercounts;
				} else {
					nextpage = currentpage + 1;
				}

				res.render('search', {
					productlist: results.productlistPager,
					currentpage: currentpage,
					previouspage: previouspage,
					nextpage: nextpage,
					pageSum: pagercounts,
					q: q,
					userInfo: results.userInfo
				});
			});
		}

	});

	//搜索产品请求方法
	app.post('/searchhandle', function(req, res) {

	});

	//将商品添加到购物车方法
	//ajax
	app.post('/cart/addhandle', function(req, res) {

		//目标跳转页面
		var target_url = '/cart';
		req.session.redirecturl = target_url;

		//用户必须先登录才能从数据库读取购物车记录并进行加载
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.status(200).send({
				url: '/login',
				message: '未登录'
			});
		} else {
			//获取表单提交数据
			var product_Id = req.body.product_Id;
			var customer_Id = userInfo.customer_Id;
			var num = req.body.goods_num;

			//设置数据对象
			var cartInfo = new CartInfo();
			cartInfo.setproduct_Id(product_Id);
			cartInfo.setcustomer_Id(customer_Id);
			cartInfo.setnum(num);

			//添加购物车数据操作
			cartDAL.addCart(cartInfo, function(message, results) {
				if(results) {
					//加入或者更新成功
					res.status(200).send({
						url: '/cart',
						message: message
					});
				}
			});
		}

	});

	//将指定商品从购物车移除
	app.get('/cart/removeGoodshandle/:id', function(req, res) {
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		var product_Id = req.params.id;
		var customer_Id = userInfo.customer_Id;
		//处理方法
		cartDAL.removeGoodsFormCart(customer_Id, product_Id, function(results) {
			if(results) {
				//删除成功
				res.redirect('/cart');
			} else {
				//删除失败
				res.redirect('/cart');
			}
		});
	});

	//递归构造树型数组对象
	function create_objectArrayList(data, pid) {
		pid = pid || 0;
		var list = [];
		data.map(function(item) {
			if(item.up_id == pid) {
				item.list = create_objectArrayList(data, item.category_Id);
				list.push(item);
			}
		});
		return list;
	}

	//移动端产品详细页面
	app.get('/mobile/product/:id',function(req,res){
	    var product_Id = req.params.id;	
	    //应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:根据产品ID获取产品所有信息
			product: function(done) {
				productDAL.getGoodsById(product_Id, function(product) {
					done(null, product);
				});
			}
		}, function(err, results) {

			//console.log(results.product);
			//res.setHeader(200, {"Content-Type": "text/html"});
			res.render('mobile/product', {
				product: results.product[0]
			});

		});	   
	});
}

module.exports = productController;